import React, { useState } from "react";
import {
  View,
  Text,
  Modal,
  Pressable,
  TextInput,
  KeyboardAvoidingView,
  Platform,
  Alert,
} from "react-native";
import { CommonActions, useNavigation } from "@react-navigation/native";
import RowButton from "@/components/Global/CustomButton/RowButton";
import styles from "./index.style";
import AvatarPicker from "@/components/Global/AvatarPicker";
import { logoutApi } from "@/services/api/login";
import TokenManager from "@/utils/token-utils";
import * as Notifications from "expo-notifications";
import CurrentUserIdManager from "@/utils/user-utils";
import { useThemeColors } from "@/theme/ThemeUtils";
import { router } from "expo-router";
import {
  useUserProfileActions,
  useUserProfileState,
} from "@/hooks/user/user-profile";
import { useStompClient } from "@/hooks/stomp/stomp-service";
import QRCodeModal from "@/components/Global/QRCodeModal";

// 验证函数
const validateUsername = (username: string) => /^\S{6,10}$/.test(username);
const validatePhone = (phone: string) => /^1[3-9]\d{9}$/.test(phone);
const validateEmail = (email: string) =>
  /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
const validateCredential = (credential: string) =>
  /^[a-zA-Z][-_a-zA-Z0-9]{5,19}$/.test(credential);
const validateResume = (resume: string) => resume.length <= 200;

export default function ProfileSettings() {
  const themeColors = useThemeColors();
  const { currentUser } = useUserProfileState();
  const { saveOrUpdateUserProfile } = useUserProfileActions();
  const { disconnect } = useStompClient();
  const navigation = useNavigation();
  const [genderModalVisible, setGenderModalVisible] = useState(false);
  const [inputModalVisible, setInputModalVisible] = useState<
    | null
    | "username"
    | "phone"
    | "email"
    | "credential"
    | "resume"
    | "gender"
    | "region"
  >(null);
  const [inputValue, setInputValue] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [qrCodeVisible, setQrCodeVisible] = useState(false);

  const getInputConfig = () => {
    switch (inputModalVisible) {
      case "username":
        return {
          title: "名称",
          placeholder: "请输入名称",
          hint: "用于展示在你的个人资料页,可以是昵称或真实姓名",
        };
      case "phone":
        return {
          title: "手机号",
          placeholder: "请输入手机号",
          hint: "请输入有效的手机号码,用于身份验证",
        };
      case "credential":
        return {
          title: "凭证ID",
          placeholder: "请输入凭证ID",
          hint: "凭证ID用于身份标识,请勿随意更改",
        };
      case "resume":
        return {
          title: "签名",
          placeholder: "请输入个性签名",
          hint: "展示在你的资料页,可以表达你的个性或状态",
        };
      case "email":
        return {
          title: "邮箱",
          placeholder: "请输入邮箱",
          hint: "用于找回密码和接收通知,请确保邮箱有效",
        };
      default:
        return null;
    }
  };

  const handleSave = () => {
    let isValid = true;
    let errorMessage = "";
    switch (inputModalVisible) {
      case "username":
        isValid = validateUsername(inputValue);
        errorMessage = "名称需为6-10个字符(支持中英文、数字、下划线和短横线）";
        break;
      case "phone":
        isValid = validatePhone(inputValue);
        errorMessage = "请输入有效的11位手机号码";
        break;
      case "email":
        isValid = validateEmail(inputValue);
        errorMessage = "请输入有效的邮箱地址";
        break;
      case "credential":
        isValid = validateCredential(inputValue);
        errorMessage = "请输入以字母开头的6-20位字母、数字、下划线或短横线";
        break;
      case "resume":
        isValid = validateResume(inputValue);
        errorMessage = "签名不能超过20个字符";
        break;
    }
    if (!isValid) {
      setError(errorMessage);
      return;
    }

    // 更新用户信息
    switch (inputModalVisible) {
      case "username":
        saveOrUpdateUserProfile({ nickname: inputValue });
        break;
      case "phone":
        saveOrUpdateUserProfile({ mobile: inputValue });
        break;
      case "email":
        saveOrUpdateUserProfile({ email: inputValue });
        break;
      case "resume":
        saveOrUpdateUserProfile({ signature: inputValue });
        break;
      case "credential":
        saveOrUpdateUserProfile({ uuid: inputValue });
        break;
    }

    setInputModalVisible(null);
    setError(null);
  };

  const getKeyboardType = () => {
    switch (inputModalVisible) {
      case "phone":
        return "numeric";
      case "email":
        return "email-address";
      default:
        return "default";
    }
  };

  const getMaxLength = () => {
    switch (inputModalVisible) {
      case "phone":
        return 11;
      case "credential":
        return 36;
      case "resume":
        return 200;
      default:
        return undefined;
    }
  };

  const handleShareQRCode = () => {
    Alert.alert("分享", "个人二维码已生成，请选择分享方式");
  };

  return (
    <View
      style={[styles.container, { backgroundColor: themeColors.background }]}
    >
      <AvatarPicker />
      <View style={[styles.divider, { backgroundColor: themeColors.border }]} />
      {/* 个人信息设置项 */}
      <RowButton
        text="名称"
        icon="person-outline"
        tailText={currentUser.nickname}
        onPress={() => {
          setInputModalVisible("username");
          setInputValue(currentUser.nickname);
        }}
      />
      <RowButton
        text="性别"
        icon="male-female-outline"
        tailText={
          currentUser.gender === 1
            ? "男"
            : currentUser.gender === 2
            ? "女"
            : "保密"
        }
        onPress={() => setGenderModalVisible(true)}
      />
      <RowButton
        text="地区"
        icon="location-outline"
        tailText={currentUser.region || "未设置"}
        onPress={() => router.navigate("/settings/region")}
      />
      <RowButton
        text="手机号"
        icon="call-outline"
        tailText={currentUser.mobile}
        onPress={() => {
          setInputModalVisible("phone");
          setInputValue(currentUser.mobile);
        }}
      />
      <RowButton
        text="邮箱"
        icon="mail-outline"
        tailText={currentUser.email}
        onPress={() => {
          setInputModalVisible("email");
          setInputValue(currentUser.email);
        }}
      />
      <RowButton
        text="凭证ID"
        icon="key-outline"
        tailText={currentUser.uuid}
        onPress={() => {
          setInputModalVisible("credential");
          setInputValue(currentUser.uuid);
        }}
      />
      <RowButton
        text="签名"
        icon="document-text-outline"
        tailText={currentUser.signature || "React Native开发者"}
        onPress={() => {
          setInputModalVisible("resume");
          setInputValue(currentUser.signature || "");
        }}
      />
      <RowButton
        text="我的二维码"
        icon="qr-code-outline"
        onPress={() => setQrCodeVisible(true)}
      />

      <RowButton
        text="退出登录"
        icon="log-out-outline"
        onPress={async () => {
          await logoutApi();
          await TokenManager.clearToken();
          await CurrentUserIdManager.clearUserId();
          disconnect();
          await Notifications.setBadgeCountAsync(0);
          navigation.dispatch(
            CommonActions.reset({
              index: 0,
              routes: [{ name: "login" }],
            })
          );
          console.log("用户已退出登录，重置导航到登录页");
        }}
      />
      {/* 性别选择模态框 */}
      <Modal
        transparent
        animationType="slide"
        visible={genderModalVisible}
        onRequestClose={() => setGenderModalVisible(false)}
      >
        <Pressable
          style={styles.modalOverlay}
          onPress={() => setGenderModalVisible(false)}
        >
          <View
            style={[
              styles.modalContent,
              { backgroundColor: themeColors.background },
            ]}
          >
            {(["男", "女", "保密"] as const).map((option) => (
              <Pressable
                key={option}
                style={[
                  styles.modalOption,
                  { borderBottomColor: themeColors.border },
                ]}
                onPress={() => {
                  let gender;
                  switch (option) {
                    case "男":
                      gender = 1;
                      break;
                    case "女":
                      gender = 2;
                      break;
                    case "保密":
                      gender = 0;
                      break;
                  }
                  // 更新用户性别
                  saveOrUpdateUserProfile({
                    gender,
                  });
                  setGenderModalVisible(false);
                }}
              >
                <Text style={[styles.modalText, { color: themeColors.text }]}>
                  {option}
                </Text>
              </Pressable>
            ))}
          </View>
        </Pressable>
      </Modal>
      {/* 通用输入模态框 */}
      <Modal
        transparent
        animationType="slide"
        visible={inputModalVisible !== null}
        onRequestClose={() => setInputModalVisible(null)}
      >
        <Pressable
          style={styles.modalOverlay}
          onPress={() => setInputModalVisible(null)}
        >
          <KeyboardAvoidingView
            behavior={Platform.OS === "ios" ? "padding" : undefined}
            style={styles.keyboardAvoidView}
          >
            <View
              style={[
                styles.inputModal,
                { backgroundColor: themeColors.background },
              ]}
            >
              <Text style={[styles.modalTitle, { color: themeColors.text }]}>
                {getInputConfig()?.title}
              </Text>
              <TextInput
                style={[
                  styles.input,
                  {
                    borderColor: error ? themeColors.error : themeColors.border,
                    color: themeColors.text,
                    backgroundColor: themeColors.card,
                  },
                  inputModalVisible === "resume"
                    ? { height: 120, paddingVertical: 12 }
                    : { height: 50, paddingVertical: 0 },
                ]}
                placeholder={getInputConfig()?.placeholder}
                value={inputValue}
                onChangeText={(text) => {
                  setInputValue(text);
                  setError(null);
                }}
                placeholderTextColor={themeColors.secondaryText}
                keyboardType={getKeyboardType()}
                maxLength={getMaxLength()}
                autoCapitalize="none"
                autoCorrect={false}
                multiline={inputModalVisible === "resume"}
                textAlignVertical={
                  inputModalVisible === "resume" ? "top" : "center"
                }
              />
              {error && (
                <Text style={[styles.errorText, { color: themeColors.error }]}>
                  {error}
                </Text>
              )}
              <Text
                style={[styles.inputHint, { color: themeColors.secondaryText }]}
              >
                {getInputConfig()?.hint}
              </Text>
              <Pressable
                style={[
                  styles.saveButton,
                  { backgroundColor: themeColors.primary },
                ]}
                onPress={handleSave}
              >
                <Text style={styles.saveText}>保存</Text>
              </Pressable>
            </View>
          </KeyboardAvoidingView>
        </Pressable>
      </Modal>

      {/* 个人二维码模态框 */}
      <QRCodeModal
        visible={qrCodeVisible}
        onClose={() => setQrCodeVisible(false)}
        type="personal"
        id={currentUser.uuid}
        name={currentUser.nickname}
        avatar={currentUser.avatar}
        onShare={handleShareQRCode}
      />
    </View>
  );
}
